'use strict';
(function(){
    var remoteVedio, wsSocket;
    var wsNews = window.WebSocket || window.MozWebSocket;
    var isConn = false;
    var roomId = "1";
    var isok   = 0;
    var clientId = ""+parseInt(Math.random()*10000);

    var pc     = null;
    var config = {"iceServers": [{"url":"stun:121.42.212.167"}, {'url':'turn:121.42.212.167', 'username':'leicc', 'credential':'simlife'}]};
    var wsUri  ="ws://121.42.212.167:8089/ws";
    remoteVedio = document.getElementById('remoteVideo');
    remoteVedio.addEventListener('loadedmetadata', function() {
        console.log('Local video videoWidth: ' + this.videoWidth + 'px,  videoHeight: ' + this.videoHeight + 'px');
        isok = 1;
    });
    console.log("client:"+clientId);
    if (!wsNews) {
        console.log('websocket not support');
    } else {
        wsSocket = new wsNews(wsUri);
        wsSocket.onopen = function() {
            console.log("connected");
            isConn  = true;
            register(roomId, clientId);
            window.setTimeout(function(){
                wsSend(roomId, clientId, "1", {Cmd:"START"});
                doDiald("1");
            }, 3000);
        };
        wsSocket.onerror = function(err) {
            console.log(err);
        };
        wsSocket.onclose = function(){
            console.log("client close!");
        };
        wsSocket.onmessage = function(evt) {
            if (isok) {
                return;
            };
            console.log("data", evt);
            wsRecv(evt.data);
        };
    };
    
    function wsRecv(data) {
        var obj  = JSON.parse(data);
        if (obj.error && obj.error != "") {
            console.log("error=="+obj.error);
            return;
        };
        var message = JSON.parse(obj.msg);
        if (!message || !message.cliidme || message.cliidme != "1") {
            console.log("filter"+message);
            return;
        };
        console.log(message, pc);
        if (pc && message.desc) {
            var desc = message.desc;
            // if we get an offer, we need to reply with an answer
            if (desc.type == "offer") {
                console.log("setRemoteDescription:"+desc);
                pc.setRemoteDescription(new RTCSessionDescription(desc)).then(function () {
                    return pc.createAnswer();
                }).then(function (answer) {
                    return pc.setLocalDescription(answer);
                }).then(function () {
                    wsSend(roomId, clientId, message.clientid, {"desc":pc.localDescription});
                }).catch(function(err){
                    console.log(err);
                });
            } else {
                pc.setRemoteDescription(new RTCSessionDescription(desc)).catch(function(err){
                    console.log(err);
                });
            }
        }
        if (pc && message.candidate) {
            console.log("addIceCandidate:"+message);
            pc.addIceCandidate(new RTCIceCandidate(message)).catch(function(err){
                console.log(err);
            });
        }
    };

    function register(roomid, clientid) {
        var data = {"Cmd":"register", "RoomID":roomid, "ClientID":clientid, "Msg":""};
        if (isConn) {
            wsSocket.send(JSON.stringify(data));
        } else {
            console.log("register websocket error!");
        }
    };

    function wsSend(roomid, mclientid, cliid, msg) {
        console.log("send to server", roomid, mclientid, cliid, msg);
        msg.cliidme = mclientid;
        var data = {"Cmd":"private", "RoomID":roomid, "ClientID":cliid, "Msg":JSON.stringify(msg)};
        if (isConn) {
            wsSocket.send(JSON.stringify(data));
        } else {
            console.log("send websocket error!");
        }
    };

    function doDiald(cliid) {
        console.log(cliid);
        pc = new RTCPeerConnection(config);
        // send any ice candidates to the other peer
        pc.onicecandidate = function (evt) {
            console.log("onicecandidate:"+evt);
            if (evt.candidate) {
                wsSend(roomId, clientId, cliid, {"label":evt.candidate.sdpMLineIndex,"candidate":evt.candidate.candidate});
            }
        };
        // let the "negotiationneeded" event trigger offer generation
        pc.onnegotiationneeded = function () {
            pc.createOffer().then(function (offer) {
                return pc.setLocalDescription(offer);
            }).then(function () {
                // send the offer to the other peer
                wsSend(roomId, clientId, cliid, {"desc":pc.localDescription});
            }).catch(function(err) {
                console.log(err);
            });
        };/**/

       

        pc.onaddstream = function(evt) {
            console.log('pc2: received remote stream');
            console.log(evt.stream);
            remoteVedio.srcObject = evt.stream;
            console.log('pc2: received remote stream');
            
        };
        console.log("add for get from queue"+pc);
    };
})();
